<template>
  <span>
    <span class="cnup_btn" @click="uploadBtnClick('uploadInput')" v-if="customType === 1" title="支持office、pdf和图片">上传资源</span>
    <span class="cnupload" @click="uploadBtnClick('uploadInput')" v-if="customType === 2" title="支持office、pdf和图片">上传</span>
    <form ref="uploadForm" style="display:none;">
      <input id="uploadInput"
             type="file"
             name="FileData"
             @change="startUpload" ref="uploadFile"/>
    </form>
    <edit-upload
        v-if="showEditUploadPop"
        @cancel-upload="cancelUpload"
        @exec-upload="executeUploading"
        :defaultTitle="defaultTitle"
    ></edit-upload>
  </span>
</template>

<script>
  import {getFileType, getFileRawName} from "../../../core/util";
  import editUpload from "./editUpload";
  import {mapMutations} from "vuex";
  import TcVod from 'vod-js-sdk-v6';

  const VIDEO_SUCC = 'video_upload';
  const VIDEO_PROG = 'video_progress';
  export default {
    name: "tencentUpload",
    components: {
      editUpload,
    },
    props: {
      // 有不同的上传按钮样式，现在只能单独定制化
      customType: {
        type: Number,
        default: 1
      },
      // 是否需要上传时填写详细信息表格
      withDetailForm: {
        type: Boolean,
        default: false
      },
      // 文件夹id，文件上传时刻（快照）的关联id
      parentID: {
        type: String,
        default: ''
      }
    },
    data() {
      return {
        // jquery由于没有加拦截器，不同站点前缀需要带上自定义url(coeduapi或subjectapi)
        uploadUrl: globalVar.baseURL + '/api/File/Upload',
        showEditUploadPop: false,
        defaultTitle: '', // 默认名称为文件名
      }
    },
    methods: {
      ...mapMutations(['toggleUploadQueuePop', 'setUploadQueue', 'updateUploadQueue']),
      uploadBtnClick(id) {
        $('#' + id).click();
      },
      /**
       * 上传文件的接口方法
       */
      uploadFile() {
        let file = this.getFileObject()
          , fileName = file.name
          , fileExt = getFileType(file.name, false, "L")
          , fileSizeNum = file.size
          , fileSizeStr = window.getProperSize(fileSizeNum)
          , rdmKey = this.getUploadKey();
        // 1. 上传队列新增一个对象
        // 2. 开没开腾讯云
        // 3. 走哪个模式上传
        this.addNewToUploadQueue({fileName, fileSizeNum, fileSizeStr, rdmKey});
        if(window.isOpenTencentVideo && this.tencentFormatCheck(fileExt)){
          // 开了腾讯云 && 视频格式
          return this.uploadToTencent({file, fileName, fileSizeNum, fileExt, rdmKey});
        }else{
          // 其他
          return this.uploadNotTencent({file, fileName, fileSizeNum, fileExt, rdmKey});
        }
      },
      /**
       * 上传队列新增一个对象
       */
      addNewToUploadQueue({fileName, fileSizeNum, fileSizeStr, rdmKey}){
        let currUploadQueue = this.$store.state.objUploadQueue;
        let type = getFileType(fileName, false, "L")
          , iconSrc = "";
        if(type.indexOf("doc") >= 0){
          iconSrc = require("../../../assets/images/sj_word.png");
        }else if(type.indexOf("xls") >= 0){
          iconSrc = require("../../../assets/images/sj_xls.png");
        }else if(type.indexOf("ppt") >= 0){
          iconSrc = require("../../../assets/images/sj_ppt.png");
        }else if(type.indexOf("pdf") >= 0){
          iconSrc = require("../../../assets/images/sj_pdf.png");
        }else if(/(png|jpg|jpeg|gif|bmp)/i.test(type)){
          iconSrc = require("../../../assets/images/sj_img.png");
        }else if(/mp3/i.test(type)){
          iconSrc = require("../../../assets/images/sj_audio.png");
        }else{
          iconSrc = require("../../../assets/images/sj_video.png");
        }
        currUploadQueue[rdmKey] = {
          fileName: fileName,
          fileSizeNum: fileSizeNum,
          fileSizeStr: fileSizeStr,
          percentage: 0,
          rdmKey: rdmKey,
          iconSrc: iconSrc
        }
        this.setUploadQueue(currUploadQueue);
      },
      /**
       * 上传资源到腾讯云上
       */
      uploadToTencent({file, fileName, fileSizeNum, fileExt, rdmKey}){
        const tcVod = new TcVod({
          getSignature: tencentGetSigAxios
        });
        let isVideoUploadSuccess = false;
        return new Promise((resolve, reject) => {
          const uploader = tcVod.upload({
            videoFile: file
          });
          uploader.on(VIDEO_SUCC, info => {
            isVideoUploadSuccess = true;
          });
          uploader.on(VIDEO_PROG, info => {
            this.updateUploadQueue({rdmKey, percentage: info.percent * 100});
          });
          uploader.done().then(res => {
            // console.log(res);
            if(isVideoUploadSuccess === true){
              resolve({
                type: 'isTencent',
                downLoadCode: res.fileId,
                uri: res.video.url,
                fileName,
                fileSizeNum,
                ext: fileExt
              })
            }else{
              this.globalShowMsg({msg: '上传腾讯云出错，请联系管理员！'});
              reject();
            }
          });
          this.resetForm();
        });
      },
      /**
       * 上传资源到非腾讯云上
       */
      uploadNotTencent({file, fileName, fileSizeNum, fileExt, rdmKey}){
        return new Promise((resolve, reject) => {
          let formdataObj = new FormData();
          formdataObj.append("FileData", file);
          $.ajax(this.uploadUrl, {
            method: 'POST',
            data: formdataObj,
            cache: false,
            dataType: "json",
            processData: false, // 必填
            contentType: false, // 必填
            success: (res) => {
              // console.log(res);
              if (res && res.Code === 200) {
                // 文件上传成功
                resolve({
                  downLoadCode: res.Data.DownLoadCode || res.Data,
                  fileName,
                  fileSizeNum,
                  ext: fileExt
                })
                this.updateUploadQueue({rdmKey, percentage: 100});
              } else {
                // 文件上传出错
                this.updateUploadQueue({rdmKey, percentage: -1});
                reject(res);
              }
            },
            error: (err) => {
              // 连接出错
              this.updateUploadQueue({rdmKey, percentage: -1});
              reject(err);
            }
          });
          this.resetForm();
        });
      },
      /**
       * 执行上传
       * @param transData 由编辑上传信息组件传递的值
       */
      executeUploading(transData) {
        let parentid = this.parentID || "";
        if(transData){
          // 关闭编辑窗口
          this.toggleUploadEditPop(false);
        }
        // 打开上传队列窗口
        this.toggleUploadQueuePop(true);
        this.uploadFile()
          .then(uploadData => {
            Object.assign(uploadData, {parentid})
            if(transData){
              this.$emit('upload-succ', {uploadData, transData})
            }else{
              this.$emit('upload-succ', uploadData);
            }
          })
          .catch(err => {
            console.log(err);
            this.globalShowMsg({msg: '出错！'})
          })
      },
      /**
       * file选中后的事件
       */
      startUpload(e) {
        let target = e.target || window.target
          , file = target.files[0];
        if (file.size === 0) {
          this.resetForm();
          return this.globalShowMsg({msg: "请选择文件大小不为0的文件！", type: "warning"});
        }
        let fileType = getFileType(file.name);
        let typeRE = /(doc|xls|ppt|pdf|png|jpg|jpeg|gif|mp3)/i;
        if(window.isOpenTencentVideo){
          // 开了腾讯云
          if(this.tencentFormatCheck(fileType)) {
            // 视频格式
            let gigabytes = file.size / 1024 / 1024 / 1024;
            if (gigabytes >= 3) {
              this.resetForm();
              return this.globalShowMsg({msg: "不支持超过3G大小的视频文件上传！", type: "warning"});
            }
          }else{
            // 非视频格式
            if(!typeRE.test(fileType)){
              this.resetForm();
              return this.globalShowMsg({msg: '暂不支持该格式的文件', type: "warning"});
            }
          }
        }else{
          // 没开腾讯云
          if(/(mp4|webm|ogg)/i.test(fileType)){
            // 视频格式
            let megabytes = file.size / 1024 / 1024;
            if (megabytes >= 500) {
              this.resetForm();
              return this.globalShowMsg({msg: "不支持超过500M大小的视频文件上传！", type: "warning"});
            }
          }else{
            // 非视频格式
            if(!typeRE.test(fileType)){
              this.resetForm();
              return this.globalShowMsg({msg: '暂不支持该格式的文件', type: "warning"});
            }
          }
        }
        if(this.withDetailForm === true){
          // 需要填写详细信息
          // 可以出现弹窗了
          this.defaultTitle = getFileRawName(file.name);
          this.toggleUploadEditPop(true); // 出现编辑上传信息的弹窗
        }else{
          // 不需要填写详细信息，直接上传
          this.executeUploading();
        }
      },
      /**
       * 重置上传表单
       */
      resetForm() {
        this.$refs['uploadForm'].reset();
      },
      /**
       * 获取当前需要上传的文件对象
       */
      getFileObject() {
        return this.$refs['uploadFile'].files[0];
      },
      /**
       * 取消上传
       */
      cancelUpload() {
        this.toggleUploadEditPop(false);
        this.resetForm();
      },
      /**
       * 切换上传后编辑的弹出层
       * @param flag
       */
      toggleUploadEditPop(flag) {
        this.showEditUploadPop = flag;
      },
      /**
       * 随机生成上传对象的键
       */
      getUploadKey() {
        let value = "";
        for (let i = 0; i < 10; i++) {
          value += this.getRandom();
        }
        return "__upload__" + value;
      },
      getRandom() {
        return Math.floor(Math.random() * 9 + 1);
      }
    },
    created() {
    }
  }
</script>

<style scoped>
  .cnup_btn {
    display: inline-block;
    color: #fff;
    font-size: 14px;
    height: 30px;
    line-height: 30px;
    background: #42a5f5 url(../../../assets/images/cnup_bdot.png) no-repeat 30px 8px;
    padding: 0px 30px 0px 50px;
    cursor: pointer;
  }

  .cnup_btn:hover {
    background-color: #2a8cd7;
  }

  .cnupload { border: 1px solid #2a8cd7; border-radius: 1px;  display: inline-block; height: 22px; line-height: 22px; color: #2a8cd7; background:#ecf9ff  url(../../../assets/images/caddot.png)no-repeat 7px -49px; padding:0px 8px 0px 20px;}
  .cnupload:hover {  background-color: #00a4e6; background-position:  7px -76px; color: #fff; cursor: pointer; }
</style>
